import 'package:flutter/services.dart';

import '../../extension/string_extension.dart';
import '../../widget/indicator/toast.dart';

/// FileName reg_exp_text_input_formatter
///
/// @Author lax
/// @Date 2024/5/14
///
/// @Description

class RegExpTextInputFormatter extends TextInputFormatter {
  /// 正则表达式
  String? pattern;

  String? message;

  RegExpTextInputFormatter({this.pattern, this.message});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String value = newValue.text;
    int selectionIndex = newValue.selection.end;
    if (value != '') {
      // 不符合正则表达式
      if (!value.regExpFormatter(pattern: pattern)) {
        value = oldValue.text;
        selectionIndex = oldValue.selection.end;
        Toast.show(message);
      }
    }
    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
